<script setup>
import { User, View } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { login } from '@/api/login'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex'

const usersFormRef = ref()
const router = useRouter()
const store = useStore()
const users = reactive({
  account: '',
  password: ''
})

const rules = reactive({
  account: [{ required: true, message: '请输入账号！', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码！', trigger: 'blur' }]
})

const onLogin =async (formEl) => {
  if(!formEl) return
  await formEl.validate(async (valid) => {
    if(valid) {
      const {account, password} = users
      try {
        const data = await login(account, password)
        console.log(data)
        store.commit('saveUserInfo', data.data)
        router.push('/')
      } catch (error) {
        console.log(error)
      }
    }
  })
}

</script>

<template>
  <div class="login">
    <div class="login-box">
      <h3 class="box-title">火星</h3>
      <el-form :model="users" status-icon :rules="rules" ref="usersFormRef">
        <el-form-item prop="account">
          <el-input type="text" size="large" :prefix-icon="User" v-model="users.account" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" size="large" :prefix-icon="View" v-model="users.password" />
        </el-form-item>
        <el-form-item>
          <el-button class="box-btn" type="primary" size="large" @click="onLogin(usersFormRef)">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .login {
    width: 100vw;
    height: 100vh;
    background-color: #f9fcff;
    display: flex;
    justify-content: center;
    align-items: center;
    .login-box {
      width: 500px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0px 0px 5px 0px #ccc;
      text-align: center;
      padding: 50px;
      .box-title {
        font-size: 30px;
        line-height: 1.5;
        font-weight: 500;
        margin-bottom: 30px;
      }
      .box-btn {
        width: 100%;
      }
    }
  }
</style>